import store from '@/store'
import { saveToken } from '@/store/actions/login'
import { logout } from '@/store/actions/profile'
import { Toast } from 'antd-mobile'
import axios, { AxiosError } from 'axios'
import history from './history'
import { getTokenInfo, setTokenInfo } from './storage'

const baseURL = 'http://geek.itheima.net/v1_0/'

// 创建实例
const http = axios.create({
  baseURL,
  timeout: 5000,
})

// 请求拦截器
http.interceptors.request.use((config) => {
  const token = getTokenInfo().token
  if (token) {
    config.headers.Authorization = `Bearer ${token}` || ''
  }
  return config
})

// 响应拦截器
http.interceptors.response.use(
  (config) => {
    return config.data
  },
  async (err: AxiosError<{ message: string }>) => {
    // 网络
    if (!err.response) {
      Toast.info('网络繁忙，请重试')
      return Promise.reject(err)
    }

    // 401
    if (err?.response?.status !== 401) {
      Toast.info(err.response.data.message)
      return Promise.reject(err)
    }

    // token过期
    const { refresh_token } = getTokenInfo()
    if (!refresh_token) {
      history.push({
        pathname: '/login',
        state: {
          from: history.location.pathname,
        },
      })
      return Promise.reject(err)
    }
    // 401错误  有刷新resfresh_token  尝试发请求获取token
    try {
      const res = await axios({
        url: baseURL + 'authorizations',
        method: 'put',
        // 请求头为刷新token
        headers: {
          Authorization: 'Bearer ' + refresh_token,
        },
      })
      // 保存最新的token
      const tokenInfo = {
        token: res.data.data.token,
        refresh_token: refresh_token,
      }
      store.dispatch(saveToken(tokenInfo))
      setTokenInfo(tokenInfo)

      // token请求成功后,再走一遍http获取内容信息
      return http(err.config)
    } catch (err) {
      // refersh_token失效  token也失效
      store.dispatch(logout())

      history.push({
        pathname: '/login',
        state: {
          from: history.location.pathname,
        },
      })
      Toast.info('登录过期')
      return Promise.reject(err)
    }
  }
)

export default http
